<template>
  <section class="demo">
    <Table v-if="list && list.length" :showSelect="false" ref="Tabular" :checkStrictly="false"
      :search-options="searchOptions" :tableDatas="list" :loading="loading" :pages="pages" :total="total"
      :columns="columns" @search="handleSearch" @delete="handleDel" @editor="handleEditor">
      <template #searchOptLeft>
        <a-button v-permission="['createFlag']" type="primary" @click="handleAdd"><i class="fa fa-plus"
            style="margin-right: 8px" />{{
              $t("New")
            }}</a-button>
      </template>
      <template #menu="{ row }">
        {{ showCurrentLang(row, isCn, isEn, isArabic) }}
      </template>
    </Table>
    <AddDialog v-if="visible" v-model:visible="visible" :target="target" @ok="handleFlush" />
  </section>
</template>

<script setup lang="ts">
import Table from "@/components/Table/index.vue";
import { queryMenus, DeleteMenu, queryPageMenus } from "@/api/setting";
import AddDialog from "./add-dialog.vue";
import { message } from "ant-design-vue";
import { showCurrentLang } from "@/utils/common/common";
import { useLanguage } from "@/hooks/index";
import { MenuLists } from "./menuColumns";
import { buildMenuTree } from "@/router/menuHelper";
const { isEn, isCn, isArabic } = useLanguage();
const { t: $t } = useI18n();
let pages = ref<object>({ pageSize: 9999999, pageNo: 1 });
let total = ref(20);
let list = ref<object>([]);
let loading = ref<boolean>(false);
let visible = ref(false);
let target = ref({});
let Tabular = ref(null);
const columns = ref<object>(new MenuLists().list());
let searchOptions = ref([
  {
    prop: "keyword",
    label: "",
    type: "inputSearch",
    default: "",
    attrs: {
      clearable: true,
    },
  },
]);
const handleSearch = async ({ searchForm, pager }: any) => {
  let requestData = {
    ...searchForm,
    ...pager,
  };
  loading.value = true;
  const { data, totalCount, pageSize, pageNo }: any = await queryPageMenus(
    requestData
  ).finally(() => {
    loading.value = false;
  });
  total.value = totalCount;
  list.value = buildMenuTree(data);
  console.log(list.value);
  pages.value.pageSize = pageSize;
  pages.value.pageNo = pageNo;
};
const handleFlush = () => {
  Tabular.value.flush();
};
const handleAdd = () => {
  target.value = {};
  visible.value = true;
};
const handleEditor = (record) => {
  target.value = cloneDeep(record);
  visible.value = true;
};
const handleDel = async (record) => {
  const id = record.id;
  if (!id) return;
  await DeleteMenu(id);
  message.success($t("操作成功"));
  handleFlush();
};
onMounted(() => {
  handleSearch({ searchForm: { keyword: "" }, pager: { pageSize: 99999999, pageNo: 1 } });
});
</script>

<style lang="scss" scoped>
.demo {
  padding: 24px 24px 0 16px;
}
</style>